/*
 * Copyright 2012 Mirella Esther da Silva
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mirella.parser.kml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.mirella.alerts.Alert;

public class KMLAlertHandler extends DefaultHandler { 

	private boolean in_kmltag = false; 
	private boolean in_placemarktag = false; 
	private boolean in_nametag = false;
	private boolean in_descriptiontag = false;
	private boolean in_geometrycollectiontag = false;
	private boolean in_linestringtag = false;
	private boolean in_pointtag = false;
	private boolean in_coordinatestag = false;
	private boolean in_linearringtag = false;
	private boolean in_styleurl = false;

	private boolean isAlert = true;

	private List<Alert> alerts = new ArrayList<Alert>();
	private Alert currentAlert; 

	public List<Alert> getAlerts() { 
		return alerts; 
	} 

	/** 
	 * This gets called at the start of an element. Here we're also setting the booleans to true if it's at that specific tag. (so we 
	 * know where we are) 
	 * 
	 * @param namespaceURI 
	 * @param localName 
	 * @param qName 
	 * @param atts 
	 * @throws SAXException 
	 */ 

	@Override 
	public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { 
		if (localName.equals("kml")) { 
			this.in_kmltag = true;
		} else if (localName.equals("Placemark")) { 
			this.in_placemarktag = true; 
			currentAlert = new Alert();
		} else if (localName.equals("name")) { 
			this.in_nametag = true;
		} else if (localName.equals("description")) { 
			this.in_descriptiontag = true;
		} else if (localName.equals("GeometryCollection")) { 
			this.in_geometrycollectiontag = true;
		} else if (localName.equals("LineString")) { 
			this.in_linestringtag = true;              
		} else if (localName.equals("point")) { 
			this.in_pointtag = true;          
		} else if (localName.equals("coordinates")) {
			this.in_coordinatestag = true;                        
		} else if (localName.equals("LinearRing")) { 
			this.in_linearringtag = true;
			this.isAlert = false;
		} else if (localName.equals("styleUrl")) { 
			this.in_styleurl = true;
		}
	} 

	/** Gets be called on closing tags like: 
	 * </tag> */ 
	@Override 
	public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
		if (localName.equals("kml")) {
			this.in_kmltag = false; 
		} else if (localName.equals("Placemark")) { 
			this.in_placemarktag = false; 
			if(this.isAlert) alerts.add(currentAlert);
			this.isAlert = true;
		} else if (localName.equals("name")) { 
			this.in_nametag = false;           
		} else if (localName.equals("description")) { 
			this.in_descriptiontag = false;
		} else if (localName.equals("GeometryCollection")) { 
			this.in_geometrycollectiontag = false;
		} else if (localName.equals("LineString")) { 
			this.in_linestringtag = false;              
		} else if (localName.equals("point")) { 
			this.in_pointtag = false;          
		} else if (localName.equals("coordinates")) { 
			this.in_coordinatestag = false;
		} else if (localName.equals("LinearRing")) { 
			this.in_linearringtag = false;
		} else if (localName.equals("styleUrl")) { 
			this.in_styleurl = false;
		}
	}

	/** Gets be called on the following structure: 
	 * <tag>characters</tag> */ 
	public void characters(char ch[], int start, int length) { 
		if(currentAlert != null && this.in_placemarktag && this.isAlert) {
			if(this.in_nametag){ 
				currentAlert.setTitle(new String(ch, start, length));            
			} else if(this.in_descriptiontag){ 
				String description = new String(ch, start, length);
				description = description.replace("<b>", "");
				description = description.replace("</b>", "");
				description = description.replace("<br/>", "\n");
				start = description.indexOf("<![CDATA[");
				length = description.indexOf("]]>");
				description = description.substring(start > -1 ? start+9 : 0, length > -1 ? length : description.length());
				currentAlert.setDescription(description);          
			} else if(this.in_coordinatestag){
				String [] coordinates = (new String(ch, start, length)).split(",");
				if(coordinates.length > 1) {
					try {
						currentAlert.setLat((int)(Double.valueOf(coordinates[1])*1E6));
						currentAlert.setLng((int)(Double.valueOf(coordinates[0])*1E6));
					} catch(Exception e) {
						Log.e("KMLAlertHandler", "Error converting '"+coordinates[1]+"' or '"+coordinates[0]+"' to double.", e);
					}
				}
			} else if(this.in_styleurl) {
				String styleUrl = new String(ch, start, length);
				if(!(styleUrl != null && (styleUrl.contains("06_to_12hr") || styleUrl.contains("00_to_06hr")))) {
					this.isAlert = false;
				}
			}
		}
	} 
} 